package com.mmz.test.thread;

import org.apache.commons.io.FileUtils;
import sun.applet.AppletClassLoader;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WriteThread implements Runnable {
    File file;
    int writeTime;
    WriteThread(String fileName, int writeTime) {
        this.file = FileUtils.getFile(fileName);
        this.writeTime = writeTime;
    }

    @Override
    public void run() {
        String currentThreadName = Thread.currentThread().getName();
        try {
            FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
            FileLock fileLock = null;
            while(true) {
                try {
                    fileLock = fileChannel.tryLock();
                    break;
                } catch (Exception e) {
                    Thread.sleep(100);
                }
            }
            fileChannel.write(ByteBuffer.wrap(("=======" + currentThreadName + "========").getBytes()));
            Thread.sleep(writeTime);

            fileLock.release();
            fileChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        String fileName = "test.test";
        Files.deleteIfExists(FileUtils.getFile(fileName).toPath());
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new WriteThread(fileName, 1000));
        executorService.execute(new WriteThread(fileName, 1000));
        executorService.execute(new WriteThread(fileName, 1000));
        executorService.execute(new WriteThread(fileName, 1000));
        executorService.execute(new WriteThread(fileName, 1000));
        executorService.execute(new WriteThread(fileName, 1000));

        Thread.sleep(2000);
        System.out.println("----");


        Thread t = new Thread();
    }

}
